package com.atguigu.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author 孔德成
 * @Slogan 致敬大师，致敬未来的你
 * @date 2021/8/9
 */
public class ThreadOrderAccess {
    public static void main(String[] args) {
        Res res = new Res();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                res.print5();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                res.print10();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                res.print15();
            }
        }, "C").start();

    }
}

class Res {
    /**
     * 一把锁，三把钥匙
     */
    Lock lock = new ReentrantLock();
    /**
     * 1 -> 执行线程 A
     * 2 -> 执行线程 B
     * 3 -> 执行线程 C
     */
    int flag = 1;
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    /**
     * 线程A
     */
    public void print5() {
        lock.lock();
        try {
            while (flag != 1) {
                condition1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            // 修改标识位
            flag = 2;
            // 通知线程B工作
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 线程B
     */
    public void print10() {
        lock.lock();
        try {
            while (flag != 2) {
                condition2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            // 修改标识位
            flag = 3;
            // 通知线程C工作
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 线程C
     */
    public void print15() {
        lock.lock();
        try {
            while (flag != 3) {
                condition3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            // 修改标识位
            flag = 1;
            // 通知线程A工作
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}
